/*
 * 版权所有(c)  1952110078@qq.com  2022 - 2022
 */

package com.ldc.commonlibs.http;

import com.ldc.commonlibs.conatants.NumberCode;
import com.ldc.commonlibs.conatants.ParamsConstants;
import com.ldc.commonlibs.http.interceptor.CookieInterceptor;
import com.ldc.commonlibs.http.interceptor.LoginInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author liudc
 * @since 2022/7/5 10:21
 */
public class RetrofitClient {
    private OkHttpClient okHttpClient;

    private RetrofitClient() {
    }


    private static class SingleTone {
        private static final RetrofitClient instance = new RetrofitClient();
    }

    /**
     * 实例化
     *
     * @return RetrofitClient
     */
    public static RetrofitClient getInstance() {
        return SingleTone.instance;
    }

    private OkHttpClient lazyClient() {
        if (okHttpClient == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .retryOnConnectionFailure(true)
                    .addInterceptor(new CookieInterceptor())
                    .addInterceptor(new LoginInterceptor())
                    .addNetworkInterceptor(ApiLogger.getLogger())
                    .writeTimeout(NumberCode.WRITE_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(NumberCode.READ_TIMEOUT, TimeUnit.SECONDS)
                    .connectTimeout(NumberCode.CONTENT_TIMEOUT, TimeUnit.SECONDS);
            okHttpClient = builder.build();
        }
        return okHttpClient;
    }


    /**
     * @param clazz 类型
     * @param <T>   模版
     * @return T
     */
    public <T> T getService(Class<T> clazz) {
        return getService(ApiConstant.BASE_URL, clazz);
    }

    /**
     * 创建服务
     *
     * @param baseUrl baseUrl
     * @param clazz   类型
     * @param <T>     模版
     * @return T
     */
    public <T> T getService(String baseUrl, Class<T> clazz) {
        return new Retrofit.Builder()
                .client(lazyClient())
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build().create(clazz);
    }
}
